# -*- coding:utf-8 -*-
import wx

# 远程解密加密
import win32crypt
import binascii
import os

class Mstsc_Pops(wx.Dialog):
    def __init__(self,grid,RowNum=-1,Data=''):
        # wx.Frame.__init__(self,None,-1,'远程桌面管理工具',pos=(800,450),size=(250,250),style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER ^ wx.MAXIMIZE_BOX)
        # super().__init__(parent=None, title='添加远程计算机',pos=(800,450),size=(350,350))
        # # 显示窗口
        # self.show_win()
        # self.Show(True)

        # 引入表格
        self.grid = grid
        self.Current_Vps = {}
        self.RowNum = RowNum
        self.Data = Data

        # wx.Frame.__init__ ( self, parent=None, id = wx.ID_ANY, title = "添加服务器", pos = wx.DefaultPosition, size = wx.Size(280,260 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
        if self.Data:
            wx.Dialog.__init__ ( self, parent=None, id = wx.ID_ANY, title = "修改服务器", pos = wx.DefaultPosition, size = wx.Size(280,260 ), style = wx.DEFAULT_DIALOG_STYLE)

            self.Icon = wx.Icon(name=os.getcwd() + "\\icon_\\" + 'horse.ico',type=wx.BITMAP_TYPE_ICO)
            self.SetIcon(self.Icon)

        else:
            wx.Dialog.__init__ ( self, parent=None, id = wx.ID_ANY, title = "添加服务器", pos = wx.DefaultPosition, size = wx.Size(280,260 ), style = wx.DEFAULT_DIALOG_STYLE)
            self.Icon = wx.Icon(name=os.getcwd() + "\\icon_\\" + 'bug.ico',type=wx.BITMAP_TYPE_ICO)
            self.SetIcon(self.Icon)

        # self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
        # self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_BTNHIGHLIGHT ) )
        
        bSizer3 = wx.BoxSizer( wx.VERTICAL )
    
        gbSizer3 = wx.GridBagSizer( 0, 0 )
        gbSizer3.SetFlexibleDirection( wx.BOTH )
        gbSizer3.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
        
        self.m_staticText1 = wx.StaticText( self, wx.ID_ANY, u"名称:", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText1.Wrap( -1 )
        gbSizer3.Add( self.m_staticText1, wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )
        
        self.m_textCtrl10 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        gbSizer3.Add( self.m_textCtrl10, wx.GBPosition( 0, 1 ), wx.GBSpan( 1, 1 ), wx.ALL|wx.EXPAND, 5 )
        
        self.m_staticText2 = wx.StaticText( self, wx.ID_ANY, u"* 计算机:", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText2.Wrap( -1 )
        self.m_staticText2.SetForegroundColour("red")
        gbSizer3.Add( self.m_staticText2, wx.GBPosition( 1, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )
        
        self.m_textCtrl11 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        gbSizer3.Add( self.m_textCtrl11, wx.GBPosition( 1, 1 ), wx.GBSpan( 1, 1 ), wx.ALL|wx.EXPAND, 5 )
        
        self.m_staticText3 = wx.StaticText( self, wx.ID_ANY, u"用户:", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText3.Wrap( -1 )
        gbSizer3.Add( self.m_staticText3, wx.GBPosition( 2, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )
        
        self.m_textCtrl12 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        
        self.m_textCtrl12.AppendText("Administrator")

        gbSizer3.Add( self.m_textCtrl12, wx.GBPosition( 2, 1 ), wx.GBSpan( 1, 1 ), wx.ALL|wx.EXPAND, 5 )
        
        self.m_staticText4 = wx.StaticText( self, wx.ID_ANY, u"* 密码:", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText4.Wrap( -1 )
        self.m_staticText4.SetForegroundColour("red")
        gbSizer3.Add( self.m_staticText4, wx.GBPosition( 3, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )
        
        self.m_textCtrl13 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        gbSizer3.Add( self.m_textCtrl13, wx.GBPosition( 3, 1 ), wx.GBSpan( 1, 1 ), wx.ALL|wx.EXPAND, 5 )
        
        self.m_staticText5 = wx.StaticText( self, wx.ID_ANY, u"备注:", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText5.Wrap( -1 )
        gbSizer3.Add( self.m_staticText5, wx.GBPosition( 4, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )
        
        self.m_textCtrl14 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        gbSizer3.Add( self.m_textCtrl14, wx.GBPosition( 4, 1 ), wx.GBSpan( 1, 1 ), wx.ALL|wx.EXPAND, 5 )
        
        m_sdbSizer2 = wx.StdDialogButtonSizer()
        self.m_sdbSizer2Save = wx.Button( self, wx.ID_SAVE )
        self.m_sdbSizer2Save.Bind(wx.EVT_BUTTON, self.Addvps, self.m_sdbSizer2Save)
        
        m_sdbSizer2.AddButton( self.m_sdbSizer2Save )

        self.m_sdbSizer2Cancel = wx.Button( self, wx.ID_CANCEL )
        self.m_sdbSizer2Cancel.Bind(wx.EVT_BUTTON, self.Closex, self.m_sdbSizer2Cancel)


        m_sdbSizer2.AddButton( self.m_sdbSizer2Cancel )
        m_sdbSizer2.Realize();
        gbSizer3.Add( m_sdbSizer2, wx.GBPosition( 5, 1 ), wx.GBSpan( 1, 1 ), wx.EXPAND, 5 )
        
        bSizer3.Add( gbSizer3, 1, wx.EXPAND, 5 )

        self.SetSizer(bSizer3)
        # self.SetSizerAndFit(sizer)

        # self.Bind(wx.EVT_KEY_DOWN,self.__onKeyDown)
        # self.Bind(wx.EVT_KEY_UP,self.__onKeyDown)
        # self.Bind(wx.EVT_CHAR_HOOK,self.__onKeyDown)
        
        # 要修改时填入数据
        self.WriteData()

        self.Centre()
        # self.Show(True)
        # Dialog 控件的显示
        self.ShowModal()

    # 无法进行键盘事件
    def __onKeyDown(self,event):
        print(event.GetKeyCode())


    # 添加新的vps
    def Addvps(self,event):
        name = self.m_textCtrl10.GetValue()
        ipx = self.m_textCtrl11.GetValue()
        user = self.m_textCtrl12.GetValue()
        passwd = self.m_textCtrl13.GetValue()
        RE = self.m_textCtrl14.GetValue()
        if ipx and passwd:
            if user:
                user = user
            else:
                user = "Administrator"

            self.Current_Vps = {"name":name,"ipx":ipx,"user":user,"passwd":passwd,"RE":RE}
            
            table  = self.grid.GetTable()
            
            if self.Data:
                TC = wx.MessageDialog(None,"是否确认更换?","更换",wx.ICON_QUESTION|wx.YES_NO)
                if TC.ShowModal() == wx.ID_YES:
                    table.Data[self.RowNum] = [name, ipx, user,passwd,RE]
                TC.Destroy()

            else:
                # 写入表格
                table.InsertRow([name, ipx, user,passwd,RE])

            self.Closex(event)

        else:
            dlg = wx.MessageDialog(self, "请检查必填项!!", "添加远程计算机", wx.OK)
            print(dir(dlg))
            dlg.ShowModal()
            dlg.Destroy()

    # 关闭弹窗
    def Closex(self,evnet):
        # print(" == Cancel Add == ")
        # self.Close()
        self.Destroy()
        return self.Current_Vps
    
    def WriteData(self):
        if self.Data:
            name,ipx,user,passwd,RE = self.Data
            self.m_textCtrl10.SetValue(name)
            self.m_textCtrl11.SetValue(ipx)
            self.m_textCtrl12.SetValue(user)
            self.m_textCtrl13.SetValue(passwd)
            self.m_textCtrl14.SetValue(RE)

    def show_win(self):
        sizer = wx.GridBagSizer(9, 9)

        Text = wx.StaticText(self,-1,"名称:")
        Text.SetForegroundColour("red")
        # sizer.Add(Text, (0, 0), (1,1))

        Text = wx.StaticText(self,-1,"计算机:")
        Text.SetForegroundColour("red")
        # sizer.Add(Text, (1, 0), (1,1))        

        Text = wx.StaticText(self,-1,"用户名:")
        Text.SetForegroundColour("red")
        # sizer.Add(Text, (2, 0), (1,1))

        Text = wx.StaticText(self,-1,"密码:")
        Text.SetForegroundColour("red")
        # sizer.Add(Text, (3, 0), (1,1))

        Text = wx.StaticText(self,-1,"备注:")
        Text.SetForegroundColour("red")
        # sizer.Add(Text, (4, 0), (1,1))

        # WB01 = wx.Button(self, -1, "添加行")
        # WB02 = wx.Button(self, -1, "添加行")
        # WB03 = wx.Button(self, -1, "添加行")
        # sizer.Add(WB01, (0, 0), (1,1))
        # sizer.Add(WB02, (0, 1), (1,1))
        # sizer.Add(WB03, (0, 3), (1,1))
        # WB01.Bind(wx.EVT_BUTTON, self.AddCol, WB01)

        self.SetSizerAndFit(sizer)
        self.Centre()



from tempfile import NamedTemporaryFile
# 设置异步的抓取
from threading import Thread

class Mstsc(Thread):
    def __init__(self,ipx,passwd,UN="Administrator"):
        super(Mstsc,self).__init__()
        self.ipx = ipx
        self.passwd = passwd
        self.UN = UN
        self.start()


    def run(self):     #定义RDP文件中数据内容
        pwdHash = win32crypt.CryptProtectData(self.passwd.encode("utf-16-le"), u'psw', None, None, None, 0) #算出密码Hash值
        pwdHash_ok = binascii.hexlify(pwdHash)
        str1 = str(pwdHash_ok).split("'")[1] #转换为字符串并使用切割法去掉内容前面的'b'，保留数据本体内容
        rdpFileStr = u'''screen mode id:i:1
            use multimon:i:0
            desktopwidth:i:1440
            desktopheight:i:900
            winposstr:s:0,1,15,15,3768,957
            session bpp:i:15
            compression:i:1
            keyboardhook:i:2
            audiocapturemode:i:0
            videoplaybackmode:i:1
            connection type:i:1
            networkautodetect:i:0
            bandwidthautodetect:i:1
            displayconnectionbar:i:1
            enableworkspacereconnect:i:0
            disable wallpaper:i:1
            allow font smoothing:i:0
            allow desktop composition:i:0
            disable full window drag:i:1
            disable menu anims:i:1
            disable themes:i:1
            disable cursor setting:i:0
            bitmapcachepersistenable:i:0
            full address:s:{ip}
            audiomode:i:2
            redirectprinters:i:0
            redirectcomports:i:0
            redirectsmartcards:i:1
            redirectclipboard:i:1
            redirectposdevices:i:0
            autoreconnection enabled:i:1
            authentication level:i:2
            prompt for credentials:i:0
            negotiate security layer:i:1
            remoteapplicationmode:i:0
            alternate shell:s:
            shell working directory:s:
            gatewayhostname:s:
            gatewayusagemethod:i:4
            gatewaycredentialssource:i:4
            gatewayprofileusagemethod:i:0
            promptcredentialonce:i:0
            gatewaybrokeringtype:i:0
            use redirection server name:i:0
            rdgiskdcproxy:i:0
            kdcproxyname:s:
            drivestoredirect:s:
            username:s:{username}
            password 51:b:{pwdHash_ok}'''.format(ip=self.ipx,username=self.UN,pwdHash_ok=str1)
        
        # 创建临时文件并远程
        with NamedTemporaryFile('w+t',prefix='Mstsc_',suffix='.rdp',encoding='utf-8',delete=False) as f:
            f.write(rdpFileStr)
        os.system("mstsc {}".format(f.name))